<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/index.js'
import { Toast } from 'vant'
import selectStore from "@/components/store/selectStore.vue";
import api from "@/api/api";
import { vw } from "@/utils/common";
import { isAndroid, isIOS, zxcxShareAction } from "@/utils/zxcxWebkit.js";
import { Decimal } from "decimal.js";

// 引入图片资源
import shareIcon from '@/assets/common/share.png'
import phoneIcon from '@/assets/my/phone.png'
import dhIcon from '@/assets/my/dh.png'

// 响应式数据
const title = ref("")
const showStore = ref(false)
const storeId = ref(-1)
const showType = ref(false)
const goodsinfo = ref({})
const storeInfo = ref({})
const id = ref(-1)
const skuList = ref([])
const showMap = ref(false)
const actions = ref([{ name: "高德地图" }])
const choiceIndex = ref(0)
const selectSkuId = ref("")
const num = ref(1)

// 路由和状态管理
const route = useRoute()
const router = useRouter()
const store = useUserStore()

// 获取位置信息
const locationInfo = computed(() => store.locationInfo)

// 计算属性
const goodsName = computed(() => {
  if (goodsinfo.value.specList) {
    let name = "";
    skuList.value.forEach((item) => {
      name += item.specValue;
    });
    return name;
  }
  return "";
})

const totalPrice = computed(() => {
  if (goodsinfo.value.price) {
    let price = new Decimal(goodsinfo.value.price);
    let total = price.times(num.value);
    return total;
  }
  return 0;
})

const desc = computed(() => {
  return htmlDecode(goodsinfo.value.intro);
})

const buy = computed(() => {
  return htmlDecode(goodsinfo.value.purchaseRules?.default);
})

// 方法定义
const onClickLeft = () => {
  router.back();
}

const getSkuName = (v) => {
  let name = "";
  v.value.forEach((item) => {
    name += item.specValue;
  });
  return name;
}

const buyNow = () => {
  if (goodsinfo.value.quantity == 0) {
    Toast("当前规格无库存，请选择其他规格");
    return;
  }
  router.push({
    path: "/makeSure",
    query: {
      id: id.value,
      skuId: goodsinfo.value.id,
      num: num.value,
    },
  });
}

const goCustomer = () => {
  router.push({
    path: "/customer",
  });
}

const back = () => {
  showStore.value = false;
}

const select = () => {
  back();
}

const getGoodsInfo = async () => {
  let res = await api.goods.getGoodsinfo({
    goodsId: id.value,
    skuId: selectSkuId.value,
  });

  goodsinfo.value = res.goodsSkuShowVo;
  goodsinfo.value.intro = htmlDecode(res.goodsSkuShowVo.intro);

  skuList.value = [];
  res.specs.forEach((item) => {
    skuList.value.push({
      id: item.skuId,
      value: item.specValues,
      price: item.price,
      quantity: item.quantity,
      pic: item.pic,
    });
  });
}

const getStoreInfo = async () => {
  let res = await api.store.getStoreDetail({
    shopId: goodsinfo.value.storeId,
  });
  storeInfo.value = res;
}

//富文本解码
const htmlDecode = (str) => {
  let s = "";
  if (!str) return "";
  if (str.length == 0) return "";
  s = str.replace(/&amp;/g, "&");
  s = s.replace(/&lt;/g, "<");
  s = s.replace(/&gt;/g, ">");
  s = s.replace(/&nbsp;/g, " ");
  s = s.replace(/&#39;/g, "'");
  s = s.replace(/&quot;/g, '"');
  s = s.replace(/&amp;/g, "&");
  s = s.replace(/class=""/gi, "");
  return s;
}

const takephone = (phone) => {
  window.location.href = `tel:${phone}`;
}

const open = () => {
  showMap.value = true;
}

const onSelect = (item, index) => {
  if (index == 0) {
    openGDMap();
  }
  onClose();
}

const onClose = () => {
  showMap.value = false;
}

const selectSku = (v, i) => {
  if (v.quantity == 0) {
    Toast("当前规格无库存，请选择其他规格");
    return;
  }
  if (choiceIndex.value == i) return;
  num.value = 1;
  choiceIndex.value = i;
  selectSkuId.value = v.id;
  getGoodsInfo();
}

const openGDMap = () => {
  let scheme = "";
  if (isAndroid()) {
    scheme = `amapuri://route/plan/?sname=我的位置&dname=${storeInfo.value.title}&dlat=${storeInfo.value.lat}&dlon=${storeInfo.value.lng}&dev=1&style=2
pkg=com.autonavi.minimap`;
  } else if (isIOS()) {
    scheme = `iosamap://path?sourceApplication=掌心长兴&sname=我的位置&dname=${storeInfo.value.title}&dlat=${storeInfo.value.lat}&dlon=${storeInfo.value.lng}&dev=1&t=0`;
  }
  const iframe = document.createElement("iframe");
  iframe.style.display = "none";
  iframe.src = scheme;
  document.body.appendChild(iframe);
  setTimeout(() => {
    document.body.removeChild(iframe);
  }, 500);
}

const share = () => {
  zxcxShareAction({
    title: `【掌心安心修】${goodsinfo.value.goodsName}`,
    desc: "交给掌心修，你就放心",
    imgUrl: goodsinfo.value.goodsGalleryList[0],
    link: `https://h5.cxbtv.cn/anxinxiushare/#/goods?id=${id.value}`,
  });
}

// 生命周期钩子
onMounted(async () => {
  id.value = route.query.goodsId;
  await getGoodsInfo();
  await getStoreInfo();
})
</script>
<template>
  <div class="serveDetail">
    <div class="pic">
      <van-swipe :autoplay="3000" :show-indicators="false" height="200">
        <van-swipe-item v-for="(image, index) in goodsinfo.goodsGalleryList" :key="index">
          <van-image width="100%" height="100%" :src="image" />
        </van-swipe-item>
      </van-swipe>
    </div>
    <div class="main">
      <div class="box">
        <div style="font-size: 12px; padding: 5px 0" class="flex flex_j_e flex_a_c" @click="share">
          <van-image :src="shareIcon" :width="vw(20)" :height="vw(20)"></van-image>
          <span style="color: #666; margin-left: 5px">分享</span>
        </div>
        <div class="flex flex_j_b flex_a_e">
          <div class="title_2">{{ goodsinfo.goodsName }}</div>
          <div class="price">￥ {{ goodsinfo.price }}</div>
        </div>
        <van-cell title="规格" is-link center @click="showType = true" />
      </div>
      <div class="box flex flex_j_b">
        <div class="label">门店</div>
        <div class="info">
          <div class="store_name">{{ storeInfo.title }}</div>
          <div class="store_num">5.0</div>
          <div class="store_address flex flex_j_b">
            <div class="area">{{ storeInfo.address }}</div>
          </div>
        </div>
        <div class="flex flex_d_c flex_j_b">
          <div class="btn_2">
            <van-image class="phone" :src="phoneIcon" @click="takephone(storeInfo.phone)" />
            <van-image class="dh" :src="dhIcon" @click="open(storeInfo.lat, storeInfo.lng)" />
          </div>
        </div>
      </div>
      <div>
        <van-divider :style="{
          color: '#282828',
          borderColor: '#282828',
          margin: '25px',
        }">购买须知
        </van-divider>
        <div class="content box" v-html="buy"></div>
      </div>
      <div class="desc">
        <van-divider :style="{
          color: '#282828',
          borderColor: '#282828',
          margin: '25px',
        }">服务详情
        </van-divider>
      </div>
      <div class="content" v-html="desc"></div>
    </div>
    <div class="bottom">
      <div class="bottom_btn_1 bottom_btn" @click="showType = true">
        立即购买
      </div>
      <div class="bottom_btn_2 bottom_btn" @click="goCustomer">联系客服</div>
    </div>
    <van-popup v-model:show="showStore" position="bottom" get-container=".serveDetail">
      <div class="main_popup">
        <selectStore v-model="storeId" @select="select" @back="back"></selectStore>
      </div>
    </van-popup>
    <van-action-sheet v-model:show="showType" :style="{ 'min-height': '70%' }" closeable>
      <div class="action_content">
        <div class="skuInfo">
          <div class="pic">
            <van-image width="100%" height="100%" :src="goodsinfo.pic" />
          </div>
          <div class="right">
            <div class="sku_price">
              <span>￥</span>
              {{ totalPrice }}
            </div>
            <div class="num">
              <van-stepper v-model="num" />
            </div>
          </div>
        </div>
        <div class="sku_type">规格</div>
        <div class="sku_list">
          <div v-for="(v, i) in skuList" :key="`${v.id}_${i}`" class="sku_item" :class="{
            select: choiceIndex == i && v.quantity != 0,
            disabled: v.quantity == 0,
          }" @click="selectSku(v, i)">
            {{ getSkuName(v) }}
          </div>
        </div>
        <div class="btn">
          <van-button type="danger" block @click="buyNow">确定</van-button>
        </div>
      </div>
    </van-action-sheet>
    <van-action-sheet v-model:show="showMap" :actions="actions" @select="onSelect" @close="onClose"
      style="font-size: 44px" />
  </div>
</template>


<style lang="less" scoped>
.serveDetail {
  min-height: 100vh;
  background: url("https://zxcxappimg.oss-cn-hangzhou.aliyuncs.com//zxcxmall/2025/05/29/44dea588672142d48f873df92c7b625e.jpg") no-repeat;
  background-size: contain;
  background-attachment: fixed;
  background-position: top;
  box-sizing: border-box;
  padding: 0 0 200px 0;

  .nav_bar {
    background: url("https://zxcxappimg.oss-cn-hangzhou.aliyuncs.com//zxcxmall/2025/05/29/44dea588672142d48f873df92c7b625e.jpg") no-repeat;
    background-size: cover;
    background-position: top center;

    :deep(.van-icon) {
      font-size: 60px;
      font-weight: bold;
      color: #fff;
    }

    :deep(.van-nav-bar__title) {
      color: #fff;
    }
  }

  :deep(.van-hairline--bottom::after) {
    border: unset;
  }

  .pic {
    width: 100%;
    max-height: 700px;
    position: relative;
  }

  .main {
    padding: 50px 50px 0 50px;
  }

  .flex {
    display: flex;
  }

  .flex_j_b {
    justify-content: space-between;
  }

  .flex_a_e {
    align-items: flex-end;
  }

  .flex_a_t {
    align-items: flex-start;
  }

  .flex_a_c {
    align-items: center;
  }

  .flex_d_c {
    flex-direction: column;
  }

  .flex_j_e {
    justify-content: end;
  }

  .title {
    font-size: 68px;
    color: #333;
    font-weight: bold;
  }

  .title_2 {
    font-size: 60px;
    color: #333;
    font-weight: bold;
    flex: 10;
  }

  .price {
    font-size: 60px;
    color: #c10500;
    font-weight: bold;
    flex-grow: 1;
  }

  .tips {
    font-size: 48px;
    color: #666666;
    margin-top: 20px;
  }

  .serve_title {
    margin-top: 75px;
    padding: 0 0 0 15px;
    font-size: 60px;
    font-weight: bold;
    border-left: 20px solid #058efb;
  }

  .box {
    padding: 45px 35px;
    margin-top: 30px;
    margin-bottom: 30px;
    background: #fff;
    border-radius: 30px;
    border: 3px solid #badefc;


    :deep(td) {
      padding-right: 50px;
    }

    :deep(p) {
      font-size: 40px;
      color: #919192;
    }

    :deep(.van-cell) {
      padding: 45px 0;
    }

    :deep(.van-cell__right-icon) {
      font-size: 50px;
    }

    .cell {
      margin-bottom: 25px;
    }

    .label {
      font-size: 40px;
      color: #919192;
    }

    .value {
      margin-left: 30px;

      .text {
        font-size: 40px;
        color: #333333;
      }
    }

    .info {
      font-size: 40px;
      max-width: 750px;

      .store_name {
        color: #333;
      }

      .store_num {
        font-size: 40px;
        color: #c10500;
      }

      .store_address {

        .distance,
        .area {
          font-size: 38px;
          color: #919192;
          text-align: left;
        }

        .distance {
          margin-right: 10px;
        }
      }
    }

    .btn {
      font-size: 38px;
      color: #058efb;
    }

    .btn_2 {
      display: flex;
      align-items: center;

      .phone {
        width: 61px;
        height: 60px;
      }

      .dh {
        width: 59px;
        height: 59px;
        margin-left: 40px;
      }
    }
  }

  .desc {
    padding: 20px 160px 30px 160px;
  }

  .content {
    font-size: 46px;

    :deep(table) {
      max-width: calc(100vw - 80px) !important;
    }
  }

  .bottom {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    height: 200px;
    padding: 10px 40px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    background-color: #fff;

    &_btn {
      height: 100px;
      padding: 0 40px;
      border-radius: 10px;
      color: #fff;
      font-size: 48px;
      line-height: 100px;
      text-align: center;
    }

    .bottom_btn_1 {
      background: #058efb;
      margin-right: 30px;
    }

    .bottom_btn_2 {
      background: #bd3023;
    }
  }

  .action_content {
    padding: 84px;

    .skuInfo {
      display: flex;
      align-items: center;

      .pic {
        max-width: 200px;
        min-width: 200px;
        height: 200px;
        aspect-ratio: 1;
      }

      .right {
        margin-left: 50px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        .sku_price {
          font-size: 60px;
          font-weight: bold;
          color: #bd3023;

          span {
            font-size: 30px;
          }
        }

        .num {
          :deep(.van-stepper__minus) {
            width: 80px;
            height: 80px;
            margin-right: 5px;
          }

          :deep(.van-stepper__input) {
            width: 120px;
            height: 80px;
            font-size: 48px;
            margin-right: 5px;
          }

          :deep(.van-stepper__plus) {
            width: 80px;
            height: 80px;
          }
        }
      }
    }

    .sku_type {
      font-size: 50px;
      color: #000;
      font-weight: bold;
    }

    .sku_list {
      display: flex;
      align-content: center;
      flex-wrap: wrap;
      padding: 30px 0;
    }

    .sku_item {
      height: 80px;
      padding: 0 30px;
      background: #f8f7fc;
      font-size: 40px;
      color: #999;
      margin: 20px 10px;
      line-height: 80px;
      text-align: center;
      border-radius: 10px;
      font-weight: bold;
    }

    .select {
      border: 1px solid #ca193d;
      background: #fee9f0;
      color: #ca193d;
    }

    .disabled {
      background-image: linear-gradient(to right, #999 0%, #999 100%);
      background-size: 100% 1px;
      background-repeat: no-repeat;
      background-position: center;
    }

    .btn {
      width: 100%;
      margin-top: 50px;
      padding: 0 40px;

      :deep(.van-button) {
        padding: 70px 100px;
        border-radius: 8px;
      }

      :deep(.van-button--normal) {
        font-size: 50px;
      }
    }
  }

  :deep(.van-cell__right-icon) {
    display: flex;
    align-items: center;
  }

  :deep(.van-cell) {
    font-size: 48px;
  }

  :deep(.van-action-sheet__close) {
    position: absolute;
    font-size: 80px;
    right: 60px;
    top: 60px;
  }
}

:deep(.van-divider) {
  font-size: 48px;
}

:deep(.van-popup--bottom.van-popup--round) {
  border-radius: 64px 64px 0 0;
}

:deep(.van-action-sheet__item) {
  padding: 80px;
}

:deep(.van-action-sheet__name) {
  font-size: 50px;
}
</style>
